package com.zhuang.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhuang.controller.utils.R;
import com.zhuang.pojo.Book;
import com.zhuang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author KangXiaoZhuang
 * @since 2021-11-13
 */
@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    // 查询
    @GetMapping
    public R getAll() {
        return new R(true, bookService.list());
    }

    // 新增
    @PostMapping
    public R save(@RequestBody Book book) throws Exception {
        if (book.getType() == null || book.getName() == null) {
            return new R(false, "图书类别或者名称为空-_-!");
        }
        boolean flag = bookService.saveBook(book);
        return new R(flag, flag ? "添加成功^_^" : "添加失败-_-!");
    }

    // 修改
    @PutMapping
    public R update(@RequestBody Book book) throws Exception {
        boolean flag = bookService.modify(book);
        return new R(flag, flag ? "修改成功^_^" : "修改失败-_-!");
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id) {
        return new R(true, bookService.getById(id));
    }

    // 删除
    @DeleteMapping("/{id}")
    public R delete(@PathVariable Integer id) {
        boolean flag = bookService.delete(id);
        return new R(flag);
    }

    // 实体数据：@RequestBody
    // 路径变量：@PathVariable
    /*@GetMapping("/{currentPage}/{pageSize}")
    public R getPage(@PathVariable Integer currentPage, @PathVariable Integer pageSize) {
        IPage<Book> page = bookService.getPage(currentPage, pageSize);
        return new R(true, page);
    }*/

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize, Book book) {
        System.out.println("参数==>" + book);
        IPage<Book> page = bookService.getPage(currentPage, pageSize, book);
        //如果当前页码值大于总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值
        if (currentPage > page.getPages()) {
            page = bookService.getPage((int) page.getPages(), pageSize, book);
        }
        return new R(true, page);
    }
}

